package com.xiang.reggie.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiang.reggie.common.BaseContext;
import com.xiang.reggie.common.Result;
import com.xiang.reggie.dto.OrderDto;
import com.xiang.reggie.entity.OrderDetail;
import com.xiang.reggie.entity.Orders;
import com.xiang.reggie.service.OrderDetailService;
import com.xiang.reggie.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 半山居雾
 * @date 2022/12/22 16:46
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;


    @PostMapping("/submit")
    public Result<String> submit(@RequestBody Orders orders) {
        orderService.submit(orders);
        return Result.success("下单成功");
    }

    @GetMapping("/userPage")
    public Result<Page> userPage(int page, int pageSize) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);

        Page<OrderDto> orderDtoPage = new Page<>();

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId());

        orderService.page(ordersPage, queryWrapper);

        BeanUtils.copyProperties(ordersPage, orderDtoPage, "records");

        List<Orders> records = ordersPage.getRecords();
        List<OrderDto> orderDtoList = records.stream().map((item) -> {
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(item, orderDto);

            Long id = item.getId();
            LambdaQueryWrapper<OrderDetail> qw = new LambdaQueryWrapper<>();
            qw.eq(OrderDetail::getOrderId, id);
            List<OrderDetail> orderDetails = orderDetailService.list(qw);
            orderDto.setOrderDetails(orderDetails);
            return orderDto;
        }).collect(Collectors.toList());

        orderDtoPage.setRecords(orderDtoList);

        return Result.success(orderDtoPage);
    }




}
